# -*- coding: utf-8 -*-
# @Time    : 2018/2/6 23:13
# @Author  : Soft
# @File    : controller.py
from module.AuthUtil import auth_required
from flask import request, jsonify
from module.class_ import clazz
from module.class_.service import ClzService, Class
from module.TimeUtils import get_class_status

@clazz.route('/add', methods=['post'])
@auth_required
def add():
    forms = dict(request.form.to_dict())
    k_time = forms.get('k_time')
    work_end_time = forms.get('k_work_endtime')
    forms['k_status'] = get_class_status(k_time=k_time, work_end_time=work_end_time)
    if forms:
        if ClzService.add(**forms):
            return jsonify(status=True, msg='添加成功')
    return jsonify(status=False, msg='添加失败')


@clazz.route('/delete/<cid>', methods=['post'])
@auth_required
def delete(cid):
    if ClzService.remove(kid=cid):
        return jsonify(status=True, msg='删除成功')
    return jsonify(status=False, msg='删除失败')


@clazz.route('/change', methods=['post'])
@auth_required
def change():
    forms = request.form.to_dict()
    cid = forms.pop('id')
    k_time = forms.get('k_time')
    work_end_time = forms.get('k_work_endtime')
    forms['k_status'] = get_class_status(k_time=k_time, work_end_time=work_end_time)
    if cid:
        if ClzService.change(cid=cid, **forms):
            return jsonify(status=True, msg='修改成功')
    return jsonify(status=False, msg='修改失败')


@clazz.route('/page', methods=['post'])
@auth_required
def page():
    pg = int(request.form.get('page', '1'))
    year = request.form.get('year', '2018')
    status = request.form.get('status')
    pages = ClzService.pages(page=pg, year=year, status=status)
    return jsonify(status=True, pages=pages)


@clazz.route('/by_year', methods=['post'])
@auth_required
def get_by_year():  # 通过年度获取已上或进行中的课程
    year = request.form.get('year', '2018')
    clz = ClzService.by_year(year)
    return jsonify(status=True, result=clz)


@clazz.route('/by_id/<kid>')
@auth_required
def get_by_id(kid):
    clz = Class.find_by_id(kid)
    if clz:
        return jsonify(status=True, result=clz)
    return jsonify(status=False, result=dict())
